'''

Case Type： 数据目录
Case Name： 数据目录删除
Create At:  2020/07/01
Owner    :  @wan005
Descption:  1、备份数据目录，停止数据库，删除data目录
2、启动数据库
3、还原数据目录
4、kill后台数据库进程
5、启动数据库

'''
import os
import sys
import unittest
import time
from yat.test import Node
from yat.test import macro

sys.path.append(sys.path[0] + "/../")
from testcase.utils.Logger import Logger
from testcase.utils.CommonSH import *
from testcase.utils.Constant import Constant
from testcase.utils.Common import Common


class Removedata(unittest.TestCase):
    sh = CommonSH()
    nodes_tuple = ('PrimaryDbUser', 'Standby1DbUser', 'Standby2DbUser')
    dbPrimaryUserNode = Node(node='PrimaryDbUser')
    dbPrimaryRootNode = Node(node='PrimaryRoot')

    @RestartDbCluster(*nodes_tuple)
    def setUp(self):
        self.log = Logger()
        self.log.info('------------Opengauss_Reliability_Dbsys_Case034.py start------------')
        self.DB_INSTANCE_PATH = macro.DB_INSTANCE_PATH
        self.com = Common()
        self.Constant = Constant()

    def test_remove_data(self):
        self.log.info('----------------------remove file-----------------------')
        cmd = f'mv {self.DB_INSTANCE_PATH} {self.DB_INSTANCE_PATH}.baktest'
        self.log.info(cmd)
        msg = self.dbPrimaryUserNode.sh(cmd).result()

        self.log.info('----------------------stop opengauss-----------------------')
        is_stop = self.sh.stopDbCluster()
        self.assertTrue(is_stop)

        self.log.info('----------------------start opengauss fail-----------------------')
        is_started = self.sh.startDbCluster()
        self.assertFalse(is_started)

        self.log.info('----------------------recover file-----------------------')
        cmd = f'mv {self.DB_INSTANCE_PATH}.baktest {self.DB_INSTANCE_PATH}'
        self.log.info(cmd)
        msg = self.dbPrimaryUserNode.sh(cmd).result()
        self.log.info(msg)

        self.log.info('----------------------kill -9 opengauss-----------------------')
        result = self.com.kill_pid(self.dbPrimaryRootNode, '9')
        self.log.info(result)

        self.log.info('----------------------start opengauss success-----------------------')
        is_started = self.sh.startDbCluster()
        self.assertTrue(is_started)

    def tearDown(self):
        # 如果数据目录不存在，则进行进行环境的清理和恢复
        cmd = f'ls -al {self.DB_INSTANCE_PATH}'
        self.log.info(cmd)
        msg = self.dbPrimaryRootNode.sh(cmd).result()
        self.log.info(msg)
        if self.Constant.NO_FILE_MSG in msg:
            re_cmd = f'mv {self.DB_INSTANCE_PATH}.baktest {self.DB_INSTANCE_PATH}'
            self.log.info(re_cmd)
            msg = self.dbPrimaryRootNode.sh(re_cmd).result()
            self.log.info(msg)

        msg = self.com.kill_pid(self.dbPrimaryRootNode, 9)
        self.log.info(msg)

        is_started = self.sh.startDbCluster()
        self.log.info(is_started)
        time.sleep(2)
